package com.iss.card.db;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;

import com.iss.card.common.ApplicationManager;
import com.iss.card.db.CardContract.Accounts;
import com.iss.card.db.CardContract.Stores;

public class DBProvider extends ContentProvider {

	static private DBCreater mDbCreater;
	
	private ContentResolver mResolver;
	
	public DBProvider(){
		
	}

	@Override
	public boolean onCreate() {
		
		mDbCreater = new DBCreater(getContext());
		return mDbCreater != null;
	}
	
	@Override
	public String getType(Uri uri) {
		
		return uri.toString();
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		String tableName = null;
		
		if(Accounts.ACCOUNT_URI.equals(uri)){
			tableName = Accounts.TABLE_NAME;
		}else if(Stores.STORE_URI.equals(uri)){
			tableName = Stores.TABLE_NAME;
		}
		Cursor cursor = mDbCreater.getDataBase().query(tableName, projection, selection,
				selectionArgs, null, null, sortOrder);
		
		//֪ͨ������������Ѿ��ı�
		cursor.setNotificationUri(mResolver, uri);

		return cursor;
	}


	@Override
	public Uri insert(Uri uri, ContentValues values) {
		
		String tableName = null;
		
		if(Accounts.ACCOUNT_URI.equals(uri)){
			tableName = Accounts.TABLE_NAME;
		}else if(Stores.STORE_URI.equals(uri)){
			tableName = Stores.TABLE_NAME;
		}

		long rowId = mDbCreater.getDataBase().insert(tableName, "", values);
		if (rowId > 0) {
			if(Accounts.ACCOUNT_URI.equals(uri)){
				ApplicationManager.accountId = rowId; //��ȡID
			}
				
			Uri rowUri = ContentUris.appendId(Accounts.ACCOUNT_URI.buildUpon(), rowId).build();
			mResolver.notifyChange(rowUri, null);
			return rowUri;
		}
		throw new SQLException("Failed to insert row into" + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		String tableName = null;
		
		if(Accounts.ACCOUNT_URI.equals(uri)){
			
			tableName = Accounts.TABLE_NAME;
		}
		int rowId = mDbCreater.getDataBase().delete(tableName, selection, selectionArgs);
		return rowId;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		
		String tableName = null;
		
		if(Accounts.ACCOUNT_URI.equals(uri)){
			
			tableName = Accounts.TABLE_NAME;
		}
		int rows = mDbCreater.getDataBase().update(tableName, values, selection, selectionArgs);
		return rows;
	}
	
	/**
	 * ����ݿ�
	 */
	public void openDatabase() {
		
		mDbCreater.openDatabase();
	}
	
	/**
	 * �ر���ݿ�
	 */
	public void closeDatabase() {
		
		mDbCreater.closeDatabase();
	}
	
	public void setContentResolver(ContentResolver cr){
		
		this.mResolver = cr;
	}


}
